import { constantRouterMap } from '@/router'

const _import = (view) => {
  if (view.indexOf('/') !== 0) {
    view = `/${view}`
  }
  return () => import(`@/views${view}.vue`)
}

// 设置路由
const makeRouterMap = (menuList) => {
  if (!menuList || menuList.length === 0) {
    return []
  }
  menuList = menuList.map(item => {
    const route = {
      path: item.url,
      name: item.menu_code,
      meta: { title: item.menu_name, icon: item.icon },
      hidden: item.hidden === '1',
      component: () => _import(item.view)()
    }

    // 递归 child
    if (item.child && item.child.length !== 0) {
      route.children = makeRouterMap(item.child)
      // 设置默认 redirect 为子路由中的第一个
      if (route.children.length !== 0) {
        route.redirect = route.children[0].path
      }
    }

    return route
  })
  return menuList
}

// 设置需要缓存的视图
const makeCachedViews = (cachedViewList, menuList) => {
  if (!menuList || menuList.length === 0) {
    return
  }
  menuList.forEach(item => {
    // 如果不是隐藏的视图，那么就cache
    if (item.hidden !== '1') {
      cachedViewList.push(item.menu_code)
    }
    // 递归child
    if (item.child && item.child.length !== 0) {
      makeCachedViews(cachedViewList, item.child)
    }
  })
}

const permission = {
  state: {
    cachedViews: [],
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    },
    SET_CACHED_VIEWS: (state, cachedViews) => {
      state.cachedViews = cachedViews
    }
  },
  actions: {
    GenerateRoutes({
      commit
    }, userInfo) {
      return new Promise(resolve => {
        const menuList = userInfo.menu_list
        if (!menuList || menuList.length === 0) {
          commit('SET_ROUTERS', [])
        } else {
          // 第一级为 / 菜单，所以直接取根中的菜单数组
          commit('SET_ROUTERS', makeRouterMap(menuList[0].child))
          const cachedViews = []
          makeCachedViews(cachedViews, menuList[0].child)
          commit('SET_CACHED_VIEWS', cachedViews)
        }
        resolve()
      })
    }
  }
}

export default permission
